package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.datatype.jsr310.DecimalUtils;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    /**
     * 员工登陆
     * @param request 用于存放登陆完的用户
     * @param employee 传入的用户信息
     * @return 返回结果
     */
    @PostMapping("/login" )
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        //提交的密码进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //根据用户名查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);
        //如果用户不存在，返回
        if(emp == null){
            return R.error("用户不存在！");
        }
        //密码比对
        if(!emp.getPassword().equals(password)){
            return R.error("密码错误！");
        }
        //查看状态，禁用返回已禁用
        if(emp.getStatus() == 0){
            return R.error("账号已禁用！");
        }
        //登陆成功，将援用id存入session,并且返回登录结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    /**
     * 退出
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理session中的用户id
        request.getSession().removeAttribute("employee");
        //返回结果
        return R.success("退出成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Employee>> getPage(int page, int pageSize, String name){
        log.info("page:{},pageSize:{},name:{}",page,pageSize,name);
        //过滤条件 （名字）添加条件构造器
        LambdaQueryWrapper <Employee>queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        Page<Employee> employeePage = new Page<>(page,pageSize);
        employeeService.page(employeePage,queryWrapper);
        return R.success(employeePage);
    }

    /**
     * 添加用户
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
        //设置初始密码，但是要md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        //Long empID = (Long) request.getSession().getAttribute("employee");
        //employee.setCreateUser(empID);
        //employee.setUpdateUser(empID);
        log.info("员工信息：{}",employee);
        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    @PutMapping
    public R<String> updata(HttpServletRequest request,@RequestBody Employee employee){
        log.info(employee.toString());

        //更新信息
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));
        employeeService.updateById(employee);
        return R.success("更新成功");
    }

    @GetMapping("/{id}")
    public R<Employee> one(@PathVariable("id") Long id){
        log.info("getByID  {}",id);
        Employee one = employeeService.getById(id);
        if(one!=null){
            return R.success(one);
        }else {
            return R.error("没有查询到!");
        }

    }
}
